package com.CatTalkApi.Servlet;

import com.CatTalkApi.DAO.DataBaseContext;
import com.CatTalkApi.DAO.Passage;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/GetPassages")
public class GetPassages extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Content-Type", "application/json;");

        System.out.println("Get Passages Method: " + req.getMethod());
        //配置跨域
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH");
        resp.setHeader("Access-Control-Allow-Headers", "authorization, content-type,token,identify");
        resp.setHeader("Access-Control-Expose-Headers", "X-forwared-port, X-forwarded-host");
        resp.setHeader("Vary", "Origin,Access-Control-Request-Method,Access-Control-Request-Headers");
        super.service(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Passage[] passages = new Passage[5];
        int indexPage = Integer.parseInt(req.getParameter("pageIndex"));
        var sqlST = String.format("SELECT * FROM `passage` order by `Passage_ID` desc LIMIT %d,5;", (indexPage - 1) * 5);
        try {
            ResultSet rSet;
            rSet = DataBaseContext.getInstance().GetStmt().executeQuery(sqlST);
            int index = 0;
            while (rSet.next()) {
                passages[index] = new Passage(rSet.getInt(2), rSet.getString("Title"), rSet.getString("Body"));
                passages[index].Id = rSet.getInt("Passage_ID");
                index++;
            }
            rSet.close();
            System.out.println("执行的SQL语句" + sqlST);
            DataBaseContext.getInstance().Close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        resp.getWriter().write(JSON.toJSONString(passages));
    }
}
